<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue" :isBack="true"><block slot="backText">返回</block><block slot="content">添加任务</block></cu-custom>
		<scroll-view scroll-x class="bg-white nav" scroll-with-animation :scroll-left="scrollLeft">
		   <view class="propertyBox">
		     <view class="cu-item" :class="index == TabCur ? 'text-green cur' : ''" v-for="(item, index) in modules" :key="index" @tap="tabSelect" :data-id="index">
		       {{ item.name }}
		     </view>
		   </view>
		 </scroll-view>
		<view title="添加任务" v-if="TabCur === 0" style="width: 100%;">
			<form v-model="task" ref="form" >
				<view class="cu-form-group" >
					<view class="title">任务名称</view>
					<input placeholder="请输入任务名称" name="name" v-model="task.taskName"></input>
				</view>
				<!-- 对标关键结果 -->
				<view class="cu-form-group" @tap="selectAlignment" v-if="!showAlignment">
					<view class="cuIcon-activityfill" style="size: 20px;" >对标关键结果</view>
					<text v-model="kr.name" style="size: 20px;" >{{ kr.name ? kr.name : tip }}</text>
				</view>
				
				<!-- 负责人 -->
				<view class="cu-form-group" :class="menuArrow ? 'arrow' : ''" @click="leaderSelect" style="display: flex; justify-content: space-between;">
				  <view class="content" style="display: flex; align-items: center;">
				    <text class="">负责人</text>
				  </view>
				  <view class="action" style="display: flex; align-items: center;">
				    <text class="text-grey text-sm">{{leader.name}}</text><text class="cuIcon-right"></text>
				  </view>
				</view>
				
				<view class="cu-form-group">
					<view class="title">类型选择</view>
					<picker @change="PickerChange" :value="index" :range="picker">
						<view class="picker">
							{{index>-1?picker[index]:'请选择任务类型'}}
						</view>
					</picker>
				</view>
				<view class="cu-form-group">
					<view class="title">级别选择</view>
					<picker @change="PickerChangeLevel" :value="indexLevel" :range="level">
						<view class="picker">
							{{indexLevel>-1?level[indexLevel]:'请选择任务级别'}}
						</view>
					</picker>
				</view> 
				<!-- <view class="cu-form-group" @tap="periodicTasksSelect">
					<view class="title">重复周期</view>
					<view class="" style="margin-left: 5px;">
						{{task.periodicTasks.type?task.periodicTasks.type:'请选择任务重复周期'}}
						<text class="cuIcon-right" style="color: gray;"></text>
					</view>
				</view> -->
				<view class="cu-form-group" >
					<view class="title">{{index==0?'选择任务日期':'开始时间'}}</view>
					<!-- <picker mode="date" :value="task.startTime" start="2015-09-01" end="2050-09-01" @change="StartDate">
						<view class="picker">
							{{task.startTime}}
						</view>
					</picker> -->
					<view>
						<xp-picker @confirm="StartDate" :year-range="yearRange"> {{task.startTime}}</xp-picker>
					</view>
				</view>
				<view class="cu-form-group" v-if="index != 0">
					<view class="title">结束时间</view>
					<!-- <picker mode="date" :value="task.endTime" :start="task.startTime" end="2050-09-01" @change="EndDate">
						<view class="picker">
							{{task.endTime}}
						</view>
					</picker> -->
					<view>
						<xp-picker @confirm="EndDate" :year-range="yearRange"> {{task.endTime}}</xp-picker>
					</view>
				</view>
				<view class="cu-form-group" :class="menuArrow ? 'arrow' : ''" @click="selectStaff" style="display: flex; justify-content: space-between;">
				  <view class="content" style="display: flex; align-items: center;">
				    <text class="">参与人</text>
				  </view>
				  <view class="action" style="display: flex; align-items: center;">
				    <view class="cu-avatar-group" v-for="item in ids" :key="item.id" style="padding: 0;">
				      <view class="cu-avatar round sm" :style="{ 'background-image': 'url(' + item.avatar + ')' }" style="margin-left: -10px;"></view>
				    </view>
				    <text class="text-grey text-sm">{{ ids.length }} 人</text>
				  </view>
				</view>
				
				<view class="cu-form-group">
					<view class="title">任务详细：</view>
					<!-- <input placeholder="请输入任务细节" name="x" v-model="task.taskDetail"></input> -->
				</view>
				<view class="cu-form-group">
					 <textarea maxlength="-1" :disabled="modalName!=null" auto-height
					 @input="textareaAInput" placeholder="点击输入任务描述" v-model="task.taskDetail"></textarea>
				</view>
				<button @click="submit" type="primary" form-type="submit" style="width: 90%;margin-top: 15px;justify-content: center;">
					确认提交
				</button>
			</form> 
			
			<!-- 弹出框选择对标的KR -->
			<!-- <popup-layer ref="popupRef" :direction="'top'" > 
				<view style="text-align: center; font-size: 20px;" class="margin-top margin-bottom" @tap="chengeCycle">{{ cycle.name }}(只能选中KR)</view>
			  <view class="content bg-gray" style="overflow-y: auto;height: 350px;">
				<view class="" v-for="(item, index) in okrList" :key="index">
				  <view class="margin margin-left margin-right" style="width: 90%;margin-left: auto;margin-right: auto; ">
					<view class="title bg-white" style="font-size: 20px; display: block; padding: 10px;border: 1px solid;">
					  {{ item.name }}
					</view>
					<view class="subtitle bg-white" style="display: block;">
					  进度：
					</view>
						<view class="bg-white" style="border: 1px solid;" v-for="(kr, index) in item.subOkrList" :key="index" >
							<view :class="{ selected: kr.selected }" @click="selectKR(kr)">
								<view class="title" style="display: block; margin-top: 5px; padding: 5px">
									{{ kr.content }}：{{ kr.name }}
								</view>
								<view class="subtitle" style="display: block; padding: 5px">
									进度：{{ kr.progress }}
								</view>
							</view>
						</view>
				  </view>
				</view>
			  </view>
			</popup-layer> -->
			
			<popup-layer ref="popupRef" :direction="'top'" >
				<view style="text-align: center; font-size: 20px;" class="margin-top margin-bottom" @tap="chengeCycle">{{ cycle.name }}(一个OKR只能选中一项)</view>
			  <view class="content bg-gray" style="overflow-y: auto;height: 450px;padding: unset;font-size: 11px;">
							<view class="custom-view" style="margin: 10px;" v-for="(item, index) in okrList" :key="index">
								<view style="border-bottom: 1px solid;">
									<view class="" style="display: flex; justify-content: space-between; align-items: center;background-color: white;">
									  <view class="title bg-white" style="font-size: 20px; padding: 10px;">
										{{ item.name }}
									  </view>
									</view>
									<div class="item-container bg-white" style=" display: flex; block;padding: 10px;">
									  <div style="display: flex; align-items: center;">
										<div>
										  负责人：{{item.leaderName}}，进度：
										</div>
										<div style="flex: 1;">
										  <liu-progressbar :textInside="false" :progress="item.progress" color="#333333" :height="'10rpx'" style="width: 300rpx;"/>
										</div>
									  </div>
									</div>
								</view>
								<view class="bg-white" style=" block;padding: 10px;" v-for="(kr, index2) in item.subOkrList" :key="index2" >
									<view :class="{ selected: kr.selected }" @click="selectKR(kr,index,index2)" style="display: flex; justify-content: space-between; align-items: center;background-color: white;">
										<view class="title" style="display: block;">
											{{ kr.content }}：{{ kr.name }}
										</view>
										<div :class="{ 'circle': true, 'selected': kr.selected }">
										  <div class="check-mark" v-if="kr.selected">&#10003;</div>
										</div>
									</view>
								</view>
							</view> 
			  </view>
						<view class="button-container" style="display: flex;">
							<button class="" style="font-size: 15px;width: 200px;flex: unset;height: 40px;border-radius: 8px;" @click="cancleSelcct">取消</button>
							<button class="confirm-button" style="border-radius: 8px;font-size: 15px;width: 200px;flex: unset;height: 40px;background-color: blue;color: white;" @click="comsumSelect">确定</button>
						</view>
			</popup-layer>
			
			<!-- 周期选择 -->
			<popup-layer ref="cyclePopupRef" :direction="'top'" > <!-- 设置弹出层的高度 -->
			<view style="text-align: center; font-size: 20px;" class="margin-top margin-bottom">周期选择</view>
			  <!-- 为弹出层内容容器添加滚动条样式 -->
			  <view class="content bg-gray" style="overflow-y: auto;height: 350px;"> <!-- 添加样式以启用垂直滚动 -->
				<view class="" v-for="(item, index) in cycleList" :key="index">
				  <view class="cu-form-group margin-top" @click="selectCycle(item)">
				  	<view class="title">
						{{item.name}}
						<span v-if="item.endTime > currentTime">(进行中)</span>
						<span v-else>(结束)</span>
					</view>
				  </view>
				</view>
			  </view>
			</popup-layer>
			
			<!-- 重复任务选择 -->
			<popup-layer ref="periodicTasksPopupRef" :direction="'top'" >
			<view style="text-align: center; font-size: 20px;display: flex;justify-content: space-between;" class="margin-top margin-bottom">
				<view class="" style="margin-left: 40rpx;" @tap="closePeriodicTasksPopupRef">
					关闭
				</view>
				<view class="">
					重复周期选择	
				</view>
				<view class="" style="margin-right: 40rpx;color: blue;" @tap="conformPeriodicTasksPopupRef">
					确定
				</view>
			</view>
			  <!-- 为弹出层内容容器添加滚动条样式 -->
			  <!-- <view class="content bg-gray" style="overflow-y: auto;height: 1100rpx;"> -->
			  <view class="content bg-gray" style="overflow-y: auto;height: 500rpx;"> <!-- 添加样式以启用垂直滚动 -->
				<view class="margin" >
					重复频率
				</view>
				<view class="bg-white"  v-for="(item , index) in periodicTasksList">
					<view class="" @tap="selectPeriodicTasks(index)" style="display: flex;">
						<view class="iconfont icon-check" style="margin-left: 30rpx;display: flex;justify-content: center;flex-direction: column;color: blue;width: 30rpx;" 
						v-if="periodicTaskSelected === index"></view>
						<view class="placeholderd" v-else></view> <!-- 占位符 -->
						<view class="margin" style="margin-left: 60rpx;">
							{{item}}
						</view>
					</view>
				</view>
				<view class="margin" >
					自定义循环
				</view>
				
				<!-- 每天循环 -->
				<view class="">
					<view class="margin" style="display: flex;">
						每<input style="margin-left: 30rpx;margin-right: 30rpx;border: 1px solid black;background-color: white;" placeholder="请输入" />天循环一次
					</view>
					<view class="cu-form-group" >
						<view class="title">循环结束时间</view>
						<picker mode="date" :value="periodDictasks.endTime" start="2015-09-01" end="2050-09-01" @change="periodicTasksEndTime" @click="clickPicker" style="">
							<view class="picker">
								{{periodDictasks.endTime}}
							</view>
						</picker>
					</view>
				</view>
				
			  </view>
			</popup-layer>
	  <text style="padding: 35px;"></text>
	  </view>
	  
		<view class="bg-white " v-if="TabCur === 1" style="width: 100%;">
			<view>
			   <uni-section title="上传附件" type="line" style="margin-top: 5px;margin-left: 10px;">
				 <view class="example-body" style="margin-top: 5px;margin-left: 10px;">
				   <uni-file-picker
					   :limit="20"
					   fileMediatype="all"
					   mode="grid"
					   @select="select"
					   @progress="progress"
					   @success="success"
					   @fail="fail"
						@delete="delFile(item)"
					 ></uni-file-picker>
				 </view>
			   </uni-section>
				<!-- <button @click="select(e)">上传文件</button> -->
				 <div class="file-list">
					  <div v-for="(file, index) in listFiles" :key="index" class="file-item">
						<div class="file-actions">
						  <view style="display: flex; justify-content: space-between;
						  margin-top: 8px;margin-bottom: 8px;border-radius: 5px;border: 1px solid gainsboro;padding: 10px;">
							<view style="margin-right: 5px;">
							  {{ file.name }}
							</view>
							<view class="" style="display: flex; justify-content: space-between;">
								<view class="cuIcon-down" style="font-size: 18px;margin-right: 10px;" @click="downloadFile(index)"></view>
								<view class="cuIcon-close" style="font-size: 18px;" @click="delFile(index)"></view>
							</view>
						  </view>
						</div>
					  </div>
					</div>
			 </view>
		</view>
	</view>
		
</template>

<script>
	import Viewer from 'viewerjs';
	import iconfont from '../../font_4280116_f6izbgedf4m/iconfont.css';
	import popupLayer from '../../components/popup-layer/popup-layer.vue';
	import request from '../../common/request';
	import common from 'common/common.js';
	import MessageSender from '@/utils/sendMessage.js';
	export default {
		components: {
			},
		data() {
			return {
				yearRange: [2020,2050],
				// 滑动导航栏
				TabCur: 0,
				scrollLeft: 0,
				modules:[
					{"name": "任务详情"},
					{"name": "附件"},
				],
				periodicTaskSelected:'',
				periodicTasksList:["每天","每周","每月"],
				// 单选
				tip: '请选择对标关键结果',
				index: -1,
				indexLevel: -1,
				picker: ['每日任务', '每周任务', '月度任务','季度任务','年度任务','单次任务'],
				level: ['最高', '较高', '普通','较低'],
				task:{
					taskName: null,
					taskDetail:null,
					taskProgress: null,
					// time: '9:00',
					startTime: this.getCurrentDate(),
					endTime: this.getCurrentDate(),
					taskType: null,
					taskLevel: null,
					cardId: null,
				},
				menuArrow: '',
				modalName: null,
				card:{},
				ids:[],
				okrList:[],
				cycleList:[],
				cycle: {},
				staff: {},
				// 上个页面传递过来的kr
				oldKr: {},
				leader:{name:''},
				kr:{name:''},
				periodDictasks:{
					endTime:'2023-9-9'
				},
				showAlignment: false,
				// 文件名
				fileNameDoc:'',
				// 文件路径
				tempFilePath:'',
				// 文件的string
				fileNames:'',
				listFiles:[],
			}
		},
		// 从上个页面获取数据
		onLoad(options){
			// 从项目详细页面添加任务
			if(options.data != undefined){
				this.card = JSON.parse(decodeURIComponent(options.data));
				if(this.card ){
					this.task.cardId = this.card.id;
					this.task.moduleId = this.card.moduleId;
					this.task.projectId = this.card.projectId;
				}
			}
			// 从kr详细页面添加任务
			if(options.oldKr != undefined){
				this.oldKr = JSON.parse(decodeURIComponent(options.oldKr));
				if(this.oldKr){
					this.task.krId = this.oldKr.id;
					this.task.okrId = this.oldKr.parentId;
					if(this.oldKr){
						this.tip = "如果不选，默认当前kr";
					}
				}
			}
			var krId = options.krId;
			if(krId){
				this.showAlignment = true;
				this.task.krId = krId;
			}
			
			// if(this.oldKr.id){
			// 	this.getAllCycle();
			// }
			this.getAllCycle();
			this.staff = uni.getStorageSync("staff");
		},
		onShow() {
			var ids = uni.getStorageSync("ids");
			this.ids = ids;
			var leader = uni.getStorageSync("leader");
			if(leader.id){
				this.leader = leader;
			}
		},
		computed: {
		    currentTime() {
				const currentDate = new Date();
				return this.formatDate(currentDate); // 获取当前时间
		    },
		},
		methods: {
			// 点击开启KR选择弹框
			selectAlignment(){
				if(this.okrMap == undefined){
					this.getOkrBycycleId();
				}
				this.$refs.popupRef.show(); // 或者 boolShow = rue
			},
			// 点击取消
			cancleSelcct(){
				this.$refs.popupRef.close();
			},
			// 点击确定
			comsumSelect(){
				this.$refs.popupRef.close();
			},
			// 获取当前时间
			getCurrentDate() {
			      const now = new Date();
			      const year = now.getFullYear();
			      const month = String(now.getMonth() + 1).padStart(2, '0');
			      const day = String(now.getDate()).padStart(2, '0');
			      return `${year}-${month}-${day}`;
			},
			// 电脑端下载文件
			downloadFile(selectIndex) {
				var item = this.listFiles[selectIndex];
				this.fileNameDoc = item.name;
				
				// var url = common.api_base_url + "/downFile/" + this.filePathDoc; //平时测试 
				var url = common.api_base_url + "/downFile/" + this.fileNameDoc; // 上服务器
				uni.downloadFile({
					url: url,
					success: res => {
						if (res.statusCode === 200) {
							let index = url.lastIndexOf(".");
							let suffix = url.substr(index+1);
							// 打开文件
							uni.openDocument({
								filePath: res.tempFilePath,
								fileType: suffix,
								showMenu: true, // 右上角菜单，可以进行分享保存
								success: function(file) {
									console.log("file-success", file)
								},
								fail() {
									console.log("预览失败")
								}
							})
						}
					}
				})
			},
			// 删除测试
			delFile(index){
				var item = this.listFiles[index];
				this.fileNameDoc = item.name;
				console.log("文件名称："+ this.fileNameDoc)
				
				this.listFiles.splice(index, 1);
				
				if(this.listFiles.length > 0){
					this.fileNames = this.listFiles.map(e=>e.name).join(",");
				}
				if(this.listFiles.length == 0){
					this.fileNames = null;
				}
				console.log(this.fileNames);
				var delItem = {
					name: this.fileNameDoc,
					id: this.task.id,
					fileNames: this.fileNames
				}
				var _this = this;
				request({
					url: common.api_base_url+'/delFile',// 上服务器
					// url: common.api_base_url+'/delFile/' + _this.filePathDoc, // 测试
					data:{
						itedelItem: delItem
					},
					method: 'POST',
					success: res => {
						
						if(!res.data.success){
							_this.listFiles.push(item);
						}
						// 文件不存在
						if(res.data.code == -20){
							_this.listFiles.splice(index, 1);
							uni.showToast({
								title:res.data.message,
								icon:"error"
							})
						}
						
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 测试文件上传
			select(e) {
				// 显示的数组
				var item ={
					name: e.tempFiles[0].name,
				}
				this.listFiles.push(item);
				this.fileNameDoc = e.tempFiles[0].name;
				this.filePathDoc = e.tempFiles[0].path;
				this.filePathDoc = this.filePathDoc.split("/")[3];
				if(this.listFiles.length > 0){
					this.fileNames = this.listFiles.map(e=>e.name).join(",");
				}
				if(this.listFiles.length == 0){
					this.fileNames = e.tempFiles[0].name;
				}
				let _this = this;
				let fileSize = e.tempFiles[0].size;
				uni.uploadFile({
					url: common.api_base_url + '/uploadFile', //真实的接口地址
					filePath: e.tempFiles[0].path,
					name: 'file',
					formData: {
					  rbacToken: uni.getStorageSync('rbacToken'),
					  date: new Date().getTime(),
					  id: _this.task.id,
					  additionalData: _this.fileNames, // 添加额外的数据
					},
					success(res) {
						var data = JSON.parse(res.data);
						console.log(data)
						// 有重复名
						if(data.code == -1){
							uni.showToast({
								title:data.message,
								icon:"error"
							})
						}
						// 不成功
						if(!data.success){
							console.log("不成功")
							_this.listFiles =  _this.listFiles.slice(0 ,-1);
						}
					}
				
				})
			},
			
			// 点击显示任务详情还是评论
			tabSelect(e) {
				this.TabCur = e.currentTarget.dataset.id;
				this.scrollLeft = (e.currentTarget.dataset.id - 1) * 60;
				if(this.TabCur == 0){
					// 显示下面的任务
				} else{
					// 显示下面的记录
				}
			},
			// 选择结束时间点击事件
			clickPicker(){
				this.$refs.periodicTasksPopupRef.close(); // 或者 boolShow = rue
			},
			// 开始时间
			periodicTasksEndTime(e) {
				this.periodDictasks.endTime = e.detail.value
				this.$refs.periodicTasksPopupRef.show(); // 或者 boolShow = rue
			},
			// 点击完成，关闭重复周期选择框
			conformPeriodicTasksPopupRef(){
				this.$refs.periodicTasksPopupRef.close(); // 或者 boolShow = rue
				if(this.periodicTaskSelected == 0){
					this.periodDictasks.type = '每天';
				} else if(this.periodicTaskSelected == 1){
					this.periodDictasks.type = '每周';
				}else if(this.periodicTaskSelected == 2){
					this.periodDictasks.type  = '每月';
				}
				this.task.periodicTasks = this.periodDictasks;
			},
			// 关闭重复选择周期框
			closePeriodicTasksPopupRef(){
				this.$refs.periodicTasksPopupRef.close(); // 或者 boolShow = rue
			},
			// 选择重复周期
			selectPeriodicTasks(index){
				this.periodicTaskSelected = index;
				
			},
			// 重复周期选中
			periodicTasksSelect(){
				this.$refs.periodicTasksPopupRef.show(); // 或者 boolShow = rue
			},
			// 选择周期
			selectCycle(cycle) {
				this.cycle = cycle;
				this.getOkrBycycleId();
				this.$refs.cyclePopupRef.close();// 或者 boolShow = false
			},
			// 选中对标kr
			selectKR(selectedKR) {
				if(selectedKR.selected){
					selectedKR.selected = false;
					this.kr = {};
				} else{
					this.kr.selected = false;
					selectedKR.selected = true;
					this.kr = selectedKR;
				}
			},
			// 获取当前周期所有的okr
			getOkrBycycleId(){
				var _this = this;
				request({
					url: common.api_base_url+'/okr/getAllOkrGroupBycycleId/',
					data:{
					},
					method: 'GET',
					success: res => {
						_this.okrMap = res.data;
						_this.okrList = _this.okrMap[_this.cycle.id];
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 点击开启周期选择弹框
			chengeCycle(){
				this.$refs.cyclePopupRef.show(); // 或者 boolShow = rue
			},
			// 获取所有周期
			getAllCycle(){
				var _this = this;
				request({
					url: common.api_base_url+'/cycle',
					data:{
					},
					method: 'GET',
					success: res => {
						_this.cycleList = res.data;
						_this.cycle = _this.cycleList[0];
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 选中负责人
			leaderSelect(){
				uni.navigateTo({
					url:'/pages/addTask/leaderStaff?leader='+ encodeURIComponent(JSON.stringify(this.leader)),
				})
			},
			
			// 选择参与人员
			selectStaff(){
				// 选中了之后，回显
				uni.navigateTo({
					url:'/pages/addTask/selectStaff?ids='+ encodeURIComponent(JSON.stringify(this.ids)),
				})
			},
			__e(){},
			// 任务描述输入框
			textareaAInput(e) {
				this.task.taskDetail = e.detail.value
			},
			// 单选任务类型
			PickerChange(e) {
				this.index = e.detail.value;
				this.task.taskType = this.picker[this.index];
			},
			// 单选任务级别
			PickerChangeLevel(e) {
				this.indexLevel = e.detail.value;
				this.task.taskLevel = this.level[this.indexLevel];
			},
			// 添加提交
			submit(){
				if(!this.task.taskName){
					uni.showToast({
						title:"名称不能为空",
						duration: 2000,
						icon:"error"
					})
					return;
				}
				if(!this.task.taskType){
					uni.showToast({
						title:"任务类型不能为空",
						duration: 2000,
						icon:"error"
					})
					return;
				}
				if(!this.task.taskLevel){
					uni.showToast({
						title:"任务级别不能为空",
						duration: 2000,
						icon:"error"
					})
					return;
				}
				// 0 为每日任务，开始时间和结束时间一致
				if(this.index == 0){ 
					this.task.endTime = this.task.startTime;
				}
				// 负责人
				if(this.leader.id){
					this.task.staffId = this.leader.id;
				}
				
				// 参与人员id，将负责人添加到参与人员里面
				if(this.ids && this.leader){
					// 将自己添加到taskAndStaff表
					this.ids = this.ids.filter(ele => ele.id !== this.leader.id);
					this.ids.push(this.leader);
				}
				
				// 参与人员id，将创建者添加到参与人员里面
				if(this.ids){
					// 将自己添加到taskAndStaff表
					this.ids = this.ids.filter(ele => ele.id !== this.staff.id);
					this.ids.push(this.staff);
					this.task.ids = this.ids.map(item => item.id);
				} else {
					this.ids =[];
					this.ids.push(this.leader);
					this.ids.push(this.staff);
					this.task.ids = this.ids.map(item => item.id);
				}
				this.task.alignmentId = this.kr.id;
				if(this.listFiles.length > 0){
					this.task.annex = this.listFiles.map(e=>e.name).join(",");
				}
				var _this = this;
				request({
					url: common.api_base_url+'/task',
					data:{
						"task": _this.task
					},
					header:{
					},
					method: 'PUT',
					success: res => {
						if(res.data.success){
							// 给任务成员发送消息
							if(_this.ids){
								// 去掉最后一个，不给自己发消息
								_this.ids.pop();
								// 如果还有
								if(_this.ids.length > 0){
									var touserTmp = _this.ids.map(item => item.userId);
									var touser = touserTmp.join("|");
									var descript = "<div class=\"gray\">%s</div> <div class=\"normal\">您有新的任务下发，请点击查看</div><div class=\"highlight\">任务发布人："+ _this.staff.name +"，任务名称："+ _this.task.taskName +"</div>";
									MessageSender.sendMessage(touser, descript)
									  .then(response => { 
										console.log('Message sent successfully:', response);
										// 在这里可以处理发送成功的逻辑
									  })
									  .catch(error => {
										console.error('Error sending message:', error);
										// 在这里可以处理发送失败的逻辑
									  });
								}
							}
							
							// 说明是从kr详情页面过来，添加renew
							if(_this.oldKr){
								_this.addRenew();
							}
							_this.ids = [];
							uni.showToast({
								title:"添加成功",
								duration: 1000
							})
							if(_this.task.cardId){
								uni.navigateBack({
								  delta: 1,
								  success: function () {
								    const pages = getCurrentPages(); // 获取当前页面栈
								    const prevPage = pages[pages.length - 1]; // 获取上一个页面实例对象
								
								    // 在当前页面中存储需要传递的参数
								    const options = {
								     projectId: _this.card.projectId,
								     moduleId: _this.card.moduleId,
								     cardId: _this.card.id,
								      // 添加其他需要传递的参数
								    };
								    // 调用上一个页面的 onLoad 方法并传递参数
								    prevPage.onLoad(options);
								  }
								});
							} else{
								// uni.navigateBack({
								//     delta: 1,
								//     success: function () {
								//         const pages = getCurrentPages(); //获取当前页面栈
								//         const prevPage = pages[pages.length - 1]; //获取上一个页面实例对象
								//         prevPage.onLoad(); //调用上一个页面的onLoad方法
								//     }
								// });
							}
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000,
								icon:"error"
							})
						}
						uni.navigateBack({
						  delta: 1, // 返回到添加页面
						});
						_this.task={
							taskName: null,
							taskDetail:null,
							taskProgress: null,
							time: '9:00',
							startTime: _this.task.startTime,
							endTime: _this.task.endTime,
							taskType: null,
						};
						_this.index = -1;
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 添加renew
			addRenew(){
				var renew = {
					staffId : this.staff.id,
					staffName: this.staff.name,
					avatar: this.staff.avatar,
					content: this.staff.name + "创建任务：" + this.task.taskName,
					okrId: this.oldKr.id,
					parentId: this.oldKr.parentId,
				}
				request({
					url: common.api_base_url+'/renew',
					data:{
						"renew": renew
					},
					header:{
					},
					method: 'PUT',
					success: res => {
						if(res.data.success){
							
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000,
								icon:"error"
							})
						}
					},
					fail: function(e) {
						uni.showToast({
							title:"唉哟，程序错误了["+JSON.stringify(e)+"]",
							icon:"loading"
						})
					},
				});
			},
			// 开始时间
			StartDate(e) {
				// this.task.startTime = e.detail.value;
				this.task.startTime = e.value
			},
			// 结束时间
			EndDate(e) {
				// this.task.endTime = e.detail.value;
				this.task.endTime = e.value
			},
			// 时间转换格式方法
			formatDate(date) {
			  const year = date.getFullYear();
			  const month = String(date.getMonth() + 1).padStart(2, '0');
			  const day = String(date.getDate()).padStart(2, '0');
			  return `${year}-${month}-${day}`;
			},
		}
	}
</script>

<style>
.popup-content {
  max-height: 500px; /* 设置最大高度为400像素，根据需要调整 */
  overflow-y: auto; /* 如果内容溢出，允许垂直滚动 */
}

.placeholderd {
	margin-left: 30rpx;
  width: 30rpx; /* 占位符的宽度 */
  height: 30rpx; /* 占位符的高度 */
  /* 占位符的样式 */
  background-color: #fff; /* 可选 */
}

/* 导航栏固定一行 */
	.propertyBox{
		flex-flow: row;
		justify-content: flex-start;
		display: flex;
	}
	/* 导航栏 */
	.cu-item {
		text-align: center;
	  flex: 1; /* 设置每个元素的宽度为50% */
	}
	
	.circle {
		    width: 30px;
		    height: 30px;
		    border-radius: 50%;
		    background-color: #dcdcdc;
		    display: inline-flex;
		    align-items: center;
		    justify-content: center;
		    cursor: pointer;
		    margin-right: 10px;
		  }
		
		  .circle.selected {
		    background-color: #99cc99; /* Selected color */
		  }
		
		  .check-mark {
		    font-size: 24px;
		    color: #fff;
		  }
	
</style>